package com.fone.player.billing.util.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.fone.player.ApplicationManage;
import com.fone.player.billing.bean.AlParasBean;
import com.fone.player.billing.bean.ChargeRecordListBean;
import com.fone.player.billing.bean.VIPProtocBean;
import com.fone.player.billing.bean.WxParasBean;
import com.fone.player.billing.util.Base64;
import com.fone.player.billing.util.HttpUtil;
import com.fone.player.client.Configure;
import com.fone.player.client.Request;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.tencent.mm.sdk.modelpay.PayReq;

public class PayEngine {
	/** 请求方式 */
	public static final int GET = 1;
	public static final int POST = 2;
	
	public int paytype = 0;
	
	public static String mWxNotifyUrl ="";
	public static String mWxNotifyPr = "";
	
	public static String formatFeeUrl(Context context,String comefrom,String url,String clid){
		if (url == null)
			return "";
		if (null == context) {
			return "";
		}
		StringBuffer output = new StringBuffer(url);
		if (!url.endsWith("&") && !url.endsWith("?")) {
			if (url.contains("?")) {
				output.append("&");
			} else {
				output.append("?");
			}
		}
		
		String tmv = android.os.Build.VERSION.RELEASE;
		if (tmv.length() > 3) {
			tmv = android.os.Build.VERSION.RELEASE.substring(0,
					android.os.Build.VERSION.RELEASE.lastIndexOf("."));
		}
		if (android.os.Build.VERSION.RELEASE.lastIndexOf(".") != -1) {
			output.append("&tmv=" + tmv);
		};
		output.append("&fmt=xml");
		output.append("&pt=0");
		output.append("&rmid=");
		output.append("&acid=");
		output.append("&clid=");
		output.append(clid);
		output.append("&comefrom=");
		output.append(comefrom);
		String formatUrl = output.toString();
		L.v("格式化url", "ConfigureFormatFeeURL:", formatUrl);
		return formatUrl;
//		return url+"&comefrom="+comefrom;
		
	}
	
	public static String getUserChargHistUrl(Context context) {
		String host = UrlConstants.FEE_SERVER+UrlConstants.FEE_CHARGE_HIS;
		String nt = getNetType(context);
		String ua = Configure.getUa();
		String cipher = Request.getInstance().getFeeCipher();
		return host+"nt="+nt+"&cipher="+cipher+"&ua="+ua;
	}
	
	
	/**
	 * 获取用户状态的url 
	 * @param context
	 * @return
	 */
	public static String getUserVipState(Context context){
		String host = UrlConstants.FEE_SERVER+UrlConstants.FEE_VIP_STATE;
		String nt = getNetType(context);
		String ua = Configure.getUa();
		String cipher = Request.getInstance().getFeeCipher();
		return host+"nt="+nt+"&cipher="+cipher+"&ua="+ua;
	}
	
	/**
	 * 获取充值url
	 * @param context
	 * @return
	 */
	public static String getChargeProUrl(Context context){
		String host = UrlConstants.FEE_SERVER+UrlConstants.FEE_CHARGE_PROTOCOL;
		String nt = getNetType(context);
		String nn = UserInfoManager.getUserNickName();
		String rt = "2";
		nn = getEncodeInfo(nn);
		String cipher = Request.getInstance().getFeeCipher();
		return host+"nt="+nt+"&cipher="+cipher+"&nn="+nn+"&rt="+rt;
	}
	//
	//http://211.151.131.243/f/ebp_ept_4?nn=5byg5LiJ&&cipher=ayRh4CVCTBHt2k5WZaHDW5wHw4v3pVP8qMMoPk34nDtTTEd8I%2Bxa%2B2kuq%2Bzk8YeS1kLJ5PRx1G%2B4r06kh%2BLzEWk15QUGQyfNXn3sKpC%2BBcNfcwPT01esZlqCoD96VXyEd50UtREhwPvafcpBi4okxfldKiufI6F%2Fx1APBVsNGYbxqw%2FlcHEUihpE6D632Mf3GEOJZk8UTPiJ372BiSpQVg%3D%3D&nt=wifi
	public static String getVIPProUrl(Context context){
		String host = UrlConstants.FEE_SERVER+UrlConstants.FEE_VIP_PROTOCOL;
		String nt = getNetType(context);
		String rt = "1";
		String nn = UserInfoManager.getUserNickName();
		nn = getEncodeInfo(nn);
		String cipher = Request.getInstance().getFeeCipher();
		StringBuffer output = new StringBuffer(host);
		output.append("nt=");
		output.append(nt);
		output.append("&cipher=");
		output.append(cipher);
		output.append("&nn=");
		output.append(nn);
		output.append("&rt=");
		output.append(rt);
		String formatUrl = output.toString();
		L.v("格式化url", "ConfigureFormatFeeURL:", formatUrl);
		return formatUrl;
	}
//	//http://211.151.131.243/f/wxp_cpc?nn=5byg5LiJ&&cipher=ayRh4CVCTBHt2k5WZaHDW5wHw4v3pVP8qMMoPk34nDtTTEd8I%2Bxa%2B2kuq%2Bzk8YeS1kLJ5PRx1G%2B4r06kh%2BLzEWk15QUGQyfNXn3sKpC%2BBcNfcwPT01esZlqCoD96VXyEd50UtREhwPvafcpBi4okxfldKiufI6F/x1APBVsNGYbxqw/lcHEUihpE6D632Mf3GEOJZk8UTPiJ372BiSpQVg%3D%3D&nt=wifi
//	public static String getVipPayUrl(Context context){
//		String host = UrlConstants.FEE_SERVER+UrlConstants.THIRD_VIP_PROTOCOL;
//		String nt = getNetType(context);
////		String ft ="2";
////		String bt ="3";
//		String nn = UserInfoManager.getUserNickName();
//		nn = getEncodeInfo(nn);
//		String cipher = Request.getInstance().getFeeCipher();
//		return host+"nt="+nt+"&cipher="+cipher+"&nn="+nn;
//	}
//	/**
//	 * 获取支付宝计费策略
//	 * @param context
//	 * @return
//	 */
//	public static String getAliPayUrl(Context context){
//		String host = UrlConstants.FEE_SERVER+UrlConstants.WX_PROTOCOL;
//		String nt = getNetType(context);
//		String ft ="2";
//		String bt ="3";
//		String cipher = Request.getInstance().getFeeCipher();
//		return host+"nt="+nt+"&ft="+ft+"&bt="+bt+"&cipher="+cipher;
//	}
	
//	/**
//	 * 获取微信计费策略
//	 * @param context
//	 * @return
//	 */
//	public static String  getWxPayUrl(Context context){
//		String host = UrlConstants.FEE_SERVER+UrlConstants.WX_PROTOCOL;
//		String nt = getNetType(context);
//		String ft ="9";
//		String bt ="9";
//		String cipher = Request.getInstance().getFeeCipher();
//		return host+"nt="+nt+"&ft="+ft+"&bt="+bt+"&cipher="+cipher;
//	}
	
//	
//	//http://211.151.131.243/f/preln?ft=3&bt=12&nt=wifi&cipher=wFhY0%2BErGTor3O1H7gPlqJwHw4v3pVP8qMMoPk34nDtTTEd8I%2Bxa%2B2kuq%2Bzk8YeS1kLJ5PRx1G%2B4r06kh%2BLzEWk15QUGQyfNXn3sKpC%2BBcNqXDKoaWX0J5TUQY1l0D%2FS0vnJ8YfO5w3bECmg6ji1FIW714DX1FWi5T5QRndGU4fxqw%2FlcHEUihpE6D632Mf3GEOJZk8UTPiJ372BiSpQVg%3D%3D
//	public static String getSPUrl(Context context){
//		String host = UrlConstants.FEE_SERVER+UrlConstants.SP_PROTOCOL;
//		String cipher = Request.getInstance().getFeeCipher();
//		String ft ="3";
//		String bt ="12";
//		String nt = getNetType(context);
//		return host+"cipher="+cipher+"&ft="+ft+"&bt="+bt+"&nt="+nt;
//	}
	
////nro?cipher=&stid=&clientcheck&ei=&pr=&ft= 
	/**
	 * 
	 * @param host 上报url
	 * @param ei	错误码
	 * @param i		0 成功 1失败
	 * @param pr	计费金额
	 * @param sid	订单号
	 * @return
	 */
	public static String getNotifyUrl(String host,String ei,int i,String pr,String sid){
//		String clientcheck_tem = "";
		if(!TextUtils.isEmpty(host)){
//			if(host.contains("?clientcheck=")){
//				clientcheck_tem = host.substring(host.indexOf("clientcheck="), host.length());
//				
//				host = host+"&cipher="+Request.getInstance().getFeeCipher();
//			}else{
			if(host.contains("sid")){
				host = host+"&cipher="+Request.getInstance().getFeeCipher()+"&clientcheck="+i+"&ei="+ei+"&pr="+pr;
			}else{
				host = host+"&cipher="+Request.getInstance().getFeeCipher()+"&clientcheck="+i+"&ei="+ei+"&pr="+pr+"&sid="+sid;
			}
				
				L.i("上报url","host:"+host);
//			}
		}else{
			L.i("上报url未获取到","host:"+host);
		}
		return host;
	}
//	public static String getWXNotifyUrl(String host,String ei,int i,String pr,String sid){
////		String clientcheck_tem = "";
//		if(!TextUtils.isEmpty(host)){
////			if(host.contains("?clientcheck=")){
////				clientcheck_tem = host.substring(host.indexOf("clientcheck="), host.length());
////				
////				host = host+"&cipher="+Request.getInstance().getFeeCipher();
////			}else{
//			host = host+"&cipher="+Request.getInstance().getFeeCipher()+"&clientcheck="+i+"&ei="+ei+"&pr="+pr+"&sid="+sid;
//			L.i("上报url","host:"+host);
////			}
//		}else{
//			L.i("上报url未获取到","host:"+host);
//		}
//		return host;
//	}
//	String mFeeUrl = UrlConstants.FEE_SERVER+UrlConstants.WX_PROTOCOL+"ft=9"+"&nt="+Request.getInstance().getFeeCipher();
	
	private static String getNetType(Context mContext){
		int type = FoneUtil.getCurrentNetType(mContext);
		if(type == 0){
			return null;
		}else if(type == 1){
			return "wifi";
		}else if(type == 2){
			return "3g";
		}else if(type == 3){
			return "gprs";
		}
		return null;
	}
	
	/**
	 * 获取包月计费策略 vb sp 三方
	 * @param url
	 * @param param
	 * @param requestType
	 */
	public static VIPProtocBean getVIPPayProto(String url,Map<String, Object>param,int requestType){
//		String rqUrl = "";
//		String type = "";
		VIPProtocBean vipProtocBean = null;
		InputStream is = getInputStreamUrl(url, param, requestType);
		try {
			InputStream ins = HttpUtil.parseInputStream(is);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = ins.read(b, 0, b.length)) != -1) {
				baos.write(b, 0, len);
			}
			ins.close();
			baos.close();
			byte [] data = baos.toByteArray();
			if(null != data && data.length > 20 ){
				String payProtocolInfo = new String (data);
				L.i("_by_Info", payProtocolInfo);
				vipProtocBean = new VIPProtocBean();
				vipProtocBean = vipProtocBean.getVipPro(payProtocolInfo);
			}
			return  vipProtocBean;
		} catch (IOException e) {
			e.printStackTrace();
			L.i("字节流解密异常", "获取字符串出错"+e.getMessage());
			return null;
		}
	}
	
	
	
//	
//	@SuppressWarnings("unused")
//	public static PayReq getWxPayInfo(String url, Map<String, Object> param,
//			int requestType) {
//		InputStream is = getInputStreamUrl(url, param, requestType);
//		try {
//		InputStream ins = HttpUtil.parseInputStream(is);
//		
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		int len = 0;
//		byte[] b = new byte[1024];
//			while ((len = ins.read(b, 0, b.length)) != -1) {
//				baos.write(b, 0, len);
//			}
//			ins.close();
//			baos.close();
//			byte [] data = baos.toByteArray();
////			return null != data && data.length > 20 ? data : null;
//			return null;
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}
//	}
	
	public static void getNotifyInfo(String url,Map<String, Object>param,int requestType){
	byte[] notifyInfo = getPayInfo(url, param, requestType);
	if(null != notifyInfo){
		String info = new String(notifyInfo);
		L.i("通知上报返回报文", info);
	}else{
		L.i("通知上报错误","上报失败");
	}
	
	}

	public static AlParasBean getAliPayInfo(String url, Map<String, Object> param,
			int requestType){
		String rurl = "" ;
		String nurl = ""; 
		String errorInfo = "";
		String errorCode = "";
		AlParasBean alParasBean;
		byte[] payInfo = getPayInfo(url, param, requestType);
		L.i("ali信息：", new String(payInfo));
		String info = new String(payInfo);
		if(TextUtils.isEmpty(info)){
			L.i("阿里为空", "直接返回");
			return null;
		}else{
			if(info.contains("ms")){
				errorInfo = info.substring(0, info.indexOf("</ms>")) ;
				errorInfo = errorInfo.substring(errorInfo.lastIndexOf(">")+1, errorInfo.length());
				L.i("获取阿里失败ms",errorInfo);
				errorCode = info.substring(0,info.indexOf("</state>"));
				errorCode = errorCode.substring(errorCode.lastIndexOf(">")+1, errorCode.length());
				L.i("获取阿里失败state",errorCode);
				return null;
			}else{
				if(!TextUtils.isEmpty(info) && info.contains("</rurl>")){
					rurl = info.substring(0, info.indexOf("</rurl>")) ;
					rurl = rurl.substring(rurl.lastIndexOf(">")+1, rurl.length());
					info = info.replace(rurl, "aa");
				}
				if(!TextUtils.isEmpty(info) && info.contains("</nurl>")){
					nurl = info.substring(0, info.indexOf("</nurl>")) ;
					nurl = nurl.substring(nurl.lastIndexOf(">")+1, nurl.length());
					info = info.replace(nurl, "aa");
				}
				L.i("替换url后", info);
//				InputStream ins = new ByteArrayInputStream(payInfo);
				InputStream ins = new ByteArrayInputStream(info.getBytes());
				alParasBean = new AlParasBean();
				alParasBean = alParasBean.parseXml(ins);
				if(null != alParasBean){
					alParasBean.setNurl(nurl);
					alParasBean.setRurl(rurl);
				}
			}
		}

		return alParasBean;
	}
	
	
	public static  PayReq  getWxInfo(String url, Map<String, Object> param,
			int requestType,int paytype) {
		PayReq req = new PayReq();
		String errorCode = "";
		String errorInfo = "";
		String rurl = ""; 
		try {
			WxParasBean wx = new WxParasBean();
			byte[] payInfo = getPayInfo(url, param, requestType);
			L.i("wx信息：", new String(payInfo));
			String wxInfo = new String(payInfo);
			if(TextUtils.isEmpty(wxInfo)){
				L.i("wx失败", "解析前文本串为空");
			}else{
				if(wxInfo.contains("error")){
					errorInfo = wxInfo.substring(0, wxInfo.indexOf("</errormsg>")) ;
					errorInfo = errorInfo.substring(errorInfo.lastIndexOf(">")+1, errorInfo.length());
					L.i("获取微信失败errorInfo:",errorInfo);
					errorCode = wxInfo.substring(0,wxInfo.indexOf("</errorcode>"));
					errorCode = errorCode.substring(errorCode.lastIndexOf(">")+1, errorCode.length());
					L.i("获取微信失败errorCode:",errorCode);
					return null;
				}else{
					if(!TextUtils.isEmpty(wxInfo) && wxInfo.contains("</rurl>")){
						rurl = wxInfo.substring(0, wxInfo.indexOf("</rurl>")) ;
						rurl = rurl.substring(rurl.lastIndexOf(">")+1, rurl.length());
						mWxNotifyUrl = rurl;
						wxInfo = wxInfo.replace(rurl, "aa");
					}
					InputStream ins = new ByteArrayInputStream(wxInfo.getBytes());
					
					wx = wx.parseXml(ins);
					//缓存微信上报url
					SharedPreferences settings = PreferenceManager
							.getDefaultSharedPreferences(ApplicationManage.getGlobalContext());
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("wxrurl", rurl);
					editor.putString("wxtof", wx.getTof());
					editor.putInt("wxtype",paytype);
					editor.commit();
					
					if(null!= wx){
						wx.setRurl(rurl);
						mWxNotifyPr = wx.getTof();
						req.appId = wx.getAppId();
						req.partnerId = wx.getPartnerId();
						req.prepayId = wx.getPrepayId();
						req.nonceStr = wx.getNonceStr();
						req.timeStamp = wx.getTimeStamp();
						req.packageValue = wx.getPackageValue();
						req.sign = wx.getSign();
					}else{
						L.i("wx为null", "微信支付订单信息解析失败");
					}
				}
			}
		} catch (Exception e) {
			return null;
		}
		return req;
	}
	

	private static byte[] getPayInfo(String url, Map<String, Object> param,
			int requestType) {
		L.i("请求支付url", url);
		InputStream is = getInputStreamUrl(url, param, requestType);
		try {
			InputStream ins = HttpUtil.parseInputStream(is);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = ins.read(b, 0, b.length)) != -1) {
				baos.write(b, 0, len);
			}
			ins.close();
			baos.close();
			byte [] data = baos.toByteArray();
			data = decoding(data);
			return null != data && data.length > 20 ?data : null;
		} catch (IOException e) {
			e.printStackTrace();
			L.i("字节流解密异常", "获取字符串出错"+e.getMessage());
			return null;
		}
	}
	private static byte[] decoding (byte[] data) {
		int length = data.length;
		for (int i = 0; i < length; ++i) {
			data[i] -= (0x70 + i % 16);
		}
		return data;
	}
	
	/**
	 * 获取IS
	 * 
	 * @param url
	 * @param param
	 * @param RequestType
	 * @return
	 */
	private static InputStream getInputStreamUrl(String url,
			Map<String, Object> param, int RequestType) {
		InputStream is = null;
		switch (RequestType) {
		case GET:
			is = ApiClient.http_get(url, null);
			break;
		case POST:
			is = ApiClient.http_post(url, param, null);
			break;
		default:
			if (null != param && param.size() > 0)
				is = ApiClient.http_post(url, param, null);
			break;
		}
		return is;
	}
	
	
	@SuppressWarnings("deprecation")
	public static String getEncodeInfo(String info){
		if (null != info && !("".equals(info.trim()))) {
			info = new String(Base64.encode(info.getBytes(),
					Base64.DEFAULT | Base64.NO_WRAP));
			info = URLEncoder.encode(info);
		}else{
			info = "aa";
			info = new String(Base64.encode(info.getBytes(),
					Base64.DEFAULT | Base64.NO_WRAP));
			info = URLEncoder.encode(info);
		}
		return info;
	}
	
//	public static String configureGetTMV() {
//		String tmv = android.os.Build.VERSION.RELEASE;
//		if (tmv.length() > 3) {
//			tmv = android.os.Build.VERSION.RELEASE.substring(0,
//					android.os.Build.VERSION.RELEASE.lastIndexOf("."));
//		}
//		if (android.os.Build.VERSION.RELEASE.lastIndexOf(".") != -1) {
//			return tmv;
//		}
//		return "";
//	}
	
	
	public static String getUserFromFeeCenter(String url, Map<String, Object> param,
			int requestType){
		byte[] payInfo = getBasicInfo(url, param, requestType);
		String userInfo=null;
		if(payInfo!=null){
		L.i("getu？返回报文：", new String(payInfo));
		userInfo = new String(payInfo);
		}
//		if()
		return userInfo;
	}
	
	private static  byte[] getBasicInfo(String url, Map<String, Object> param,
			int requestType){
		InputStream is = getInputStreamUrl(url, param, requestType);
		if(is==null){
			return null;
		}
		try {
			InputStream ins = HttpUtil.parseInputStream(is);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = ins.read(b, 0, b.length)) != -1) {
				baos.write(b, 0, len);
			}
			ins.close();
			baos.close();
			byte [] data = baos.toByteArray();
			if(null != data && data.length > 20 ){
				String payProtocolInfo = new String (data);
				L.i("返回报文", payProtocolInfo);
			}
			return  data;
		} catch (IOException e) {
			e.printStackTrace();
			L.i("解析异常", "获取字符串出错"+e.getMessage());
			return null;
		}
	}

	public static ChargeRecordListBean getUserChargeList(String url, Map<String, Object> param,
			int requestType){
		byte[] payInfo = getBasicInfo(url, param, requestType);
		if(payInfo==null){
			return null;
		}
		ChargeRecordListBean listRst = new ChargeRecordListBean();
		 ByteArrayInputStream ins = new ByteArrayInputStream(payInfo);
		 listRst = listRst.parseXml(ins);
		
		L.i("_record_info：", new String(payInfo));
		String userInfo = new String(payInfo);
		L.i("",userInfo);
		
		return listRst;
	}
}
